package com.gitee.feizns.quickstart.ding.talk.spring.boot.autoconfigure;

import com.dingtalk.open.app.api.GenericEventListener;
import com.gitee.feizns.quickstart.ding.talk.Config;
import com.gitee.feizns.quickstart.ding.talk.api.top.api.ContactsApi;
import com.gitee.feizns.quickstart.ding.talk.api.v10.oauth2.AccessToken;
import com.gitee.feizns.quickstart.ding.talk.event.DingTalkStreamEventListener;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;

import java.util.List;

/**
 * 钉钉自动配置
 * @author feizns
 * @since 2025/3/27
 */
@AutoConfiguration
@RequiredArgsConstructor
@EnableConfigurationProperties(QuickstartDingTalkProperties.class)
public class QuickstartDingTalkAutoconfigure {

    /**
     * 属性
     */
    private final QuickstartDingTalkProperties properties;

    /**
     * 钉钉相关配置
     * @return {@link AccessToken }
     */
    @Lazy
    @Bean
    public Config dingTalkConfig() {
        return properties.toConfig();
    }

    /**
     * 访问令牌
     * @return {@link AccessToken }
     */
    @Lazy
    @Bean
    public AccessToken accessToken(Config config) {
        return new AccessToken(config);
    }

    /**
     * 联系人 API
     * @param accessToken 访问令牌
     * @return {@link ContactsApi }
     */
    @Lazy
    @Bean
    public ContactsApi contactsApi(AccessToken accessToken) {
        return new ContactsApi(accessToken);
    }

    /**
     * 钉钉流事件监听器
     * @param genericEventListeners 通用事件侦听器
     * @return {@link DingTalkStreamEventListener }
     */
    @Bean
    @ConditionalOnBean(GenericEventListener.class)
    public DingTalkStreamEventListener dingTalkStreamEventListener(List<GenericEventListener> genericEventListeners) {
        DingTalkStreamEventListener dingTalkStreamEventListener = new DingTalkStreamEventListener(properties.toConfig());
        genericEventListeners.forEach(dingTalkStreamEventListener::register);
        dingTalkStreamEventListener.start();
        return dingTalkStreamEventListener;
    }

}
